package cn.kooki.app.duobao.ui.Activity.Comm;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.widget.Toast;

import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.LoginResponse;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.bus.LoginChangeEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.User.BindActivity;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2016/1/30.
 */
public class AuthVerifyActivity extends BaseActivity {

    public UMShareAPI mShareAPI;

    @Override
    protected void setToolbar() {

    }

    @Override
    protected void setLayoutContentView() {
        mShareAPI = UMShareAPI.get(this);
        int type = getIntent().getIntExtra("type", 0);
        dologinOther(type);
    }

    @Override
    protected void afterView() {

    }

    public void dologinOther(int type) {
        SHARE_MEDIA platform = null;

        switch (type) {
            case 0:
                platform = SHARE_MEDIA.WEIXIN;

                break;
            case 1:
                platform = SHARE_MEDIA.QQ;

                break;
            case 2:
                platform = SHARE_MEDIA.SINA;
                break;
        }
        mShareAPI.doOauthVerify(this, platform, umAuthListener);
    }


    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            mShareAPI.getPlatformInfo(AuthVerifyActivity.this, platform, infoListener);
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
            finish();

        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
            finish();
        }
    };

    public void doLoginOther(final int type, final String username, String img, String openid) {
        showLoading(getString(R.string.login_loading));
        HashMap<String, Object> others = new HashMap<>();
        others.put("openid", openid);
        others.put("username", username);
        others.put("img", img);
        MainFactory.getApiInstance().register(type, 4, others, new Callback<LoginResponse>() {
            @Override
            public void success(LoginResponse loginResponse, Response response) {
                if (loginResponse.getData() != null) {
                    UserInfo userInfo = loginResponse.getData();
                    SharePreferencesUtils.putUserinfo(AuthVerifyActivity.this, userInfo);
                    SharePreferencesUtils.putBoolean(AuthVerifyActivity.this, SharePreferencesUtils.ISLOGIN, true);
                    MobclickAgent.onProfileSignIn(type + "", userInfo.getUid());
                    JPushInterface.setAlias(getApplicationContext(), userInfo.getUid(), null);
                    if (TextUtils.isEmpty(userInfo.getMobile())) {
                        Intent intent = new Intent(AuthVerifyActivity.this, BindActivity.class);
                        startActivity(intent);
                    }
                    onOtherLoginComplete();
                } else {
                    onLoginFair("登录失败");
                }
            }


            @Override
            public void failure(RetrofitError error) {
                onLoginFair(getString(R.string.network_error));
            }
        });
    }


    private UMAuthListener infoListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            KLog.i(map.toString());

            if (share_media == SHARE_MEDIA.WEIXIN) {
                String openid = map.get("openid");
                String imgurl = map.get("headimgurl");
                String username = map.get("nickname");
                doLoginOther(Constants.LOGINTYPE_WEIXIN, username, imgurl, openid);
            } else if (share_media == SHARE_MEDIA.QQ || share_media == SHARE_MEDIA.QZONE) {
                String openid = map.get("openid");
                String imgurl = map.get("profile_image_url");
                String username = map.get("screen_name");
                doLoginOther(Constants.LOGINTYPE_QQ, username, imgurl, openid);
            }

        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mShareAPI.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void onLoginFair(String msg) {
        dismissLoading();
        showToastMessage(msg);
        finish();
    }

    public void onOtherLoginComplete() {
        LoginChangeEvent event = new LoginChangeEvent();
        event.islogin = true;
        EventBus.getDefault().post(event);
        finish();
    }
}
